package com.itheima.controller;

import com.itheima.pojo.Emp;
import com.itheima.pojo.EmpQueryParam;
import com.itheima.pojo.PageResult;
import com.itheima.pojo.Result;
import com.itheima.service.EmpService;
import jakarta.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@RestController
@RequestMapping("/emps")
public class EmpController {

    @Autowired
    private EmpService empService;

    /**
     * 分页条件查询
     * 接收多个普通参数(?key=value&key2=value2)，不要加@RequestParam注解
     * @RequestBody(json {key:value,key2:value2...})
     */
    @GetMapping//接收请求
    public Result page(EmpQueryParam empQueryParam){//接收参数
        //int[] arr = {1,2};
        //System.out.println("arr[2] = " + arr[2]);
        //int i = 1/0;
        log.info("分页查询，参数：" + empQueryParam);
        //调用业务层
        PageResult<Emp> pageResult = empService.page(empQueryParam);
        //响应数据
        return Result.success(pageResult);
    }

    /**
     * 新增员工
     * @param emp
     * @return
     */
    @PostMapping
    public Result add(@RequestBody @Valid Emp emp) throws Exception {
        log.info("新增员工: {}", emp);
        empService.add(emp);
        return Result.success();
    }

    @DeleteMapping
    //使用数组接收带逗号分隔的参数值，参数名与方法参数名一致
    //使用集合来接收，注意必须添加@RequestParam注解
    public Result delete(@RequestParam List<Integer> ids){
        log.info("删除员工:{}", ids);
        //调用业务删除
        empService.deleteByIds(ids);
        return Result.success();
    }

    /**
     * 通过id查询员工
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public Result getById(@PathVariable Integer id){
        Emp emp = empService.getById(id);
        return Result.success(emp);
    }

    /**
     * 修改员工
     * @param emp
     * @return
     */
    @PutMapping
    public Result update(@RequestBody Emp emp){
        log.info("修改员工: {}", emp);
        empService.update(emp);
        return Result.success();
    }
}
